import { spliteMatrix } from './spliteMatrix';

export type typ_body_posi_direct = 'top' | 'left';

export type typ_posi_offset_str =
  | 'offsetHeight'
  | 'offsetLeft'
  | 'offsetTop'
  | 'offsetWidth';

/**
 * 获取 元素 视窗 的 位置 信息 及 长 宽
 * @param elt 元素
 */
export function getElementViewOffsetPosi(elt: HTMLElement) {
  let viewOffsetPosi = getElementOffsetPosi(elt);

  return {
    width: viewOffsetPosi['width'],
    height: viewOffsetPosi['height'],
    offsetTop: getbodyOffsetPosition(elt, 'top'),
    offsetLeft: getbodyOffsetPosition(elt, 'left'),
  };
}

function getElementOffsetPosi(elt: HTMLElement) {
  let getcompEl = window.getComputedStyle(elt);
  let matrixstr = getcompEl['transform'];

  let width = elt.offsetWidth;
  let height = elt.offsetHeight;
  return {
    offsetTop:
      matrixstr != 'none'
        ? spliteMatrix(matrixstr, 'translateY')
        : elt.offsetTop,
    offsetLeft:
      matrixstr != 'none'
        ? spliteMatrix(matrixstr, 'translateX')
        : elt.offsetLeft,
    width,
    height,
  };
}

function getbodyOffsetPosition(el: HTMLElement, str: typ_body_posi_direct) {
  let keys: typ_posi_offset_str = ('offset' +
    str[0].toUpperCase() +
    str.substring(1)) as any;

  let translateDire: 'translateY' | 'translateX' =
    str == 'top' ? 'translateY' : 'translateX';
  // console.log(keys);
  let num = 0;
  let elclone = el;
  for (; elclone != null; ) {
    // console.log(elclone);
    // console.log(window.getComputedStyle(elclone));
    let matrixstr = window.getComputedStyle(elclone)['transform'];
    if (matrixstr != 'none') {
      let trans = spliteMatrix(matrixstr, translateDire);
      // console.log('tran', trans);
      num += Number(trans);
    }
    // console.log(elclone, elclone['offsetParent']);
    num += Number(elclone[keys]);
    // console.log('curMix', keys, num);
    elclone = elclone['offsetParent'] as HTMLElement;
  }
  return num;
}
